<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="接口名称" prop="interfaceName">
        <el-input
          v-model="queryParams.interfaceName"
          placeholder="请输入接口名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接口路径" prop="interfacePath">
        <el-input
          v-model="queryParams.interfacePath"
          placeholder="请输入接口路径"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:interface:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:interface:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:interface:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:interface:export']"
        >导出</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="interfaceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" prop="id" />
      <el-table-column label="接口名称" align="center" prop="interfaceName" />
      <el-table-column label="接口编码" align="center" prop="interfaceCode" />
      <el-table-column label="请求类型" align="center" prop="requestType" />
        <el-table-column label="接口路径" align="center" prop="interfacePath" />
      <el-table-column label="前置接口集合" align="center" prop="frontIds" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:interface:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:interface:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改接口信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row >
          <!--部门数据-->
          <el-col :span="8" :xs="24">
            <el-form-item label="接口名称" prop="interfaceName">
              <el-input v-model="form.interfaceName" placeholder="请输入接口名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item label="接口编码" prop="interfaceCode">
              <el-input v-model="form.interfaceCode" placeholder="请输入接口编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item label="接口路径" prop="interfacePath">
              <el-input v-model="form.interfacePath" placeholder="请输入接口路径" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" :xs="24">
            <el-form-item label="请求类型" prop="requestType">
              <el-select v-model="form.requestType"  placeholder="请选择">
                <el-option label="GET" value="get"></el-option>
                <el-option label="POST" value="post"></el-option>
                <el-option label="PUT" value="put"></el-option>
                <el-option label="DELETE" value="delete"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="前置接口" prop="frontIds">
              <el-select v-model="form.frontIds" multiple placeholder="请选择前置接口"@change="setFronts">
                <el-option
                  v-for="item in frontInterfaces"
                  :key="item.id"
                  :label="item.interfaceName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24" :xs="24">
            <el-form-item label="请求头" prop="header">
              <div style="width: 98%;max-height: 200px;background-color: #f5f5ff;overflow: auto" >
                <div style="display: flex;flex-wrap: wrap; text-align:center;background-color: #e3f6ff">
                  <div style="width: 180px">参数名</div>
                  <div style="width: 180px">参数类型</div>
                  <div style="width: 180px">参数值</div>
                  <div style="width: 110px">操作</div>
                </div>
              <el-form class="base-form" ref="headerForm" :model="headerForm" :rules="rules" auto-complete="on">
                <el-table :show-header="false" ref="table-input" class="table" highlight-current-row :data="headerForm.headerList" @row-click="selectHeaderItem">
                  <el-table-column width="180px" label="参数名称">
                    <template slot-scope="scope">
                      <el-form-item :prop="'headerList.'+scope.$index+'.headerName'" :rules="rules.headerName" class="all" >
                        <!--                            <el-input style="width: 85px" v-model="scope.row.paramsName" placeholder="请输入" clearable @focus="$refs.headerForm.clearValidate(`paramsList.${scope.$index}.paramsName`)"></el-input>-->
                        <select-tree v-model="scope.row.headerName" @selectNode = "selectNode" :scopeRow = "scope.row" :scopeType = "headerType" style="width: 100%" :options = headerOption></select-tree>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column width="180px" label="参数类型">
                    <template slot-scope="scope">
                      <el-form-item :prop="'headerList.'+scope.$index+'.headerType'" :rules="rules.headerType" class="all">
                        <el-select v-model="scope.row.headerType" placeholder="请选择" clearable @focus="$refs.headerForm.clearValidate(`headerList.${scope.$index}.headerType`)">
                          <el-option label="string" value="string"></el-option>
                          <el-option label="number" value="number"></el-option>
                          <el-option label="list" value="list"></el-option>
                        </el-select>
<!--                        <el-input v-model="scope.row.headerType" placeholder="请输入" clearable @focus="$refs.headerForm.clearValidate(`headerList.${scope.$index}.headerType`)"></el-input>-->
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column width="180px" label="参数值">
                    <template slot-scope="scope">
                      <el-form-item :prop="'headerList.'+scope.$index+'.headerValue'" :rules="rules.headerValue" class="all">
                        <el-input v-model="scope.row.headerValue" placeholder="请输入" clearable @focus="$refs.headerForm.clearValidate(`headerList.${scope.$index}.headerValue`)"></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column  width="120px" prop="" label="操作">
                    <template>
                      <div class="flex-c-a">
                        <span @click="addHeaderLine()" class="add-btn">增加</span>
                        <span class="delete-btn">删除</span>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" :xs="24">
            <el-form-item label="请求参数" prop="params">
              <div style="width: 98%;max-height: 200px;background-color: #f5f5ff;overflow: auto" >
                <div style="display: flex;flex-wrap: wrap; text-align:center;background-color: #e3f6ff">
                  <div style="width: 180px">参数名</div>
                  <div style="width: 180px">参数类型</div>
                  <div style="width: 180px">参数值</div>
                  <div style="width: 110px">操作</div>
                </div>
                  <el-form class="base-form" ref="paramsForm" :model="paramsForm" :rules="rules" auto-complete="on">
                    <el-table :show-header="false" ref="table-input" class="table" highlight-current-row :data="paramsForm.paramsList" @row-click="selectItem">
                      <el-table-column width="180px" label="参数名称">
                        <template slot-scope="scope">
                          <el-form-item :prop="'paramsList.'+scope.$index+'.paramsName'" :rules="rules.paramsName" class="all" >
<!--                            <el-input style="width: 85px" v-model="scope.row.paramsName" placeholder="请输入" clearable @focus="$refs.paramsForm.clearValidate(`paramsList.${scope.$index}.paramsName`)"></el-input>-->
                              <select-tree v-model="scope.row.paramsName" @selectNode = "selectNode" :scopeRow = "scope.row" :scopeType = "paramsType" style="width: 100%" :options = paramsOption></select-tree>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column width="180px" label="参数类型">
                        <template slot-scope="scope">
                          <el-form-item :prop="'paramsList.'+scope.$index+'.paramsType'" :rules="rules.paramsType" class="all">
                            <el-select v-model="scope.row.paramsType" placeholder="请输入" clearable @focus="$refs.paramsForm.clearValidate(`paramsList.${scope.$index}.paramsType`)">
                              <el-option label="string" value="string"></el-option>
                              <el-option label="number" value="number"></el-option>
                              <el-option label="list" value="list"></el-option>
                            </el-select>
<!--                            <el-input v-model="scope.row.paramsType" placeholder="请输入" clearable @focus="$refs.paramsForm.clearValidate(`paramsList.${scope.$index}.paramsType`)"></el-input>-->
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column width="180px" label="参数值">
                        <template slot-scope="scope">
                          <el-form-item :prop="'paramsList.'+scope.$index+'.paramsValue'" :rules="rules.paramsValue" class="all">
                            <el-input v-model="scope.row.paramsValue" placeholder="请输入" clearable @focus="$refs.paramsForm.clearValidate(`paramsList.${scope.$index}.paramsValue`)"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column  width="120px" prop="" label="操作">
                        <template>
                          <div class="flex-c-a">
                            <span @click="addParamsLine()" class="add-btn">增加</span>
                            <span class="delete-btn">删除</span>
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" :xs="24">
            <el-form-item label="返回值" prop="result">
              <el-tree
                :data="rebackData"
                node-key="id"
                default-expand-all
                :expand-on-click-node="false">
                <p class="custom-tree-node" slot-scope="{ node, data }">
                  <el-input v-model="data.label"   class="small-width-ipt" placeholder="节点名称"></el-input>
                  <el-select v-model="data.type"  placeholder="节点类型"  class="small-width-select">
                    <el-option  v-for="item in selectOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                  <el-input v-model="data.comment"  class="small-width-ipt" placeholder="备注"></el-input>
                  <el-switch size="mini" v-model="data.status" active-text="正常" inactive-text="禁用"  active-value="0" inactive-value="1">
                  </el-switch>
                  <span class="actions">
                    <el-button
                      type="text"
                      icon="el-icon-plus"
                      @click="() => append(data)">
                    </el-button>
                    <el-button
                      type="text"
                      icon="el-icon-close"
                      class="delete-btn"
                      v-if="!data.isRoot"
                      @click="() => remove(node, data)">
                    </el-button>
                  </span>
                </p>
              </el-tree>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="previewInfo">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--  回显   -->
    <el-dialog title = "内容预览" :visible.sync="openPreView" width="800px" append-to-body>
        <el-table :data="previewForm" style="width: 100%;">
            <el-table-column prop ="tableName" label=""></el-table-column>
        </el-table>
        {{previewForm}}
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="cancelPre">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInterface,
  getInterface,
  delInterface,
  addInterface,
  updateInterface,
  getAllInterface, getFrontInterfaces, previewInfo
} from '@/api/business/interface'
import "@/views/business/interface/selectTree.vue"
import selectTree from '@/views/business/interface/selectTree.vue'
import row from 'element-ui/packages/row'

let id =1000;
export default {
  name: "Interface",
  computed: {
    row() {
      return row
    }
  },
  components: { selectTree },
  data() {
    return {
      selectOpt:[
        {
          label:'string',
          value:'string',
        },{
          label:'Object',
          value:'object'
        },{
          label:'list',
          value:'list'
        },
        {
          label:'number',
          value:'number'
        }
      ],
      rebackData: [{
        id: 1,
        label: '根目录',
        type:'Object',
        status:"0",
        comment:'根目录',
        isRoot:true,
        children: [],
      }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 接口信息表格数据
      interfaceList: [],
      frontInterfaces:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        interfaceName: null,
        interfaceCode: null,
        requestType: null,
        header: null,
        params: null,
        result: null,
        interfacePath: null,
        relationTables: null,
        frontIds: null,
        postIds: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      paramsType:"params",
      headerType:"header",
      tableData:[{}],
      headerTableData:[{}],
      paramsOption:undefined,
      headerOption:undefined,
      paramsForm: {
        paramsList: [
          {
            paramsName: "",
            paramsType: "",
            paramsValue: ""
          }
        ]
      },
      headerForm: {
        headerList: [
          {
            headerName: "",
            headerType: "",
            headerValue: ""
          }
        ]
      },
      openPreView:false,
      previewForm:{}
    }
  },
  created() {
    this.getList();
    this.getAllInterface();
    this.getFrontInterfaces()
  },
  methods: {
    setFronts(val){
      getAllInterface(val)
    },
    selectNode(node){
    },
    getAllInterface(frontIds){
      getAllInterface(frontIds).then(res=>{
        this.paramsOption = res.data
        this.headerOption = res.data
      })
    },
    getFrontInterfaces(){
      getFrontInterfaces().then(res=>{
        this.frontInterfaces = res.data;
      })
    },
    // 增加一个空行, 用于录入或显示第一行
    addParamsLine() {
      const newLine = {
        paramsName: "",
        paramsType: "",
        paramsValue: ""
      }
      this.index++
      this.paramsForm.paramsList.push(newLine)
    },
    addHeaderLine() {
      const newLine = {
        headerName: "",
        headerType: "",
        headerValue: ""
      }
      this.index++
      this.headerForm.headerList.push(newLine)
    },
    // 选中某一行修改或移除
    selectItem(row, column, event) {
      this.selectedFundRow = row
      if (event.target.innerText == "删除") {
        this.removeFundBtn(this.selectedFundRow)
      }
    },
    // 删除指定行
    removeFundBtn(params) {
      this.paramsForm.paramsList = this.paramsForm.paramsList.filter((ele) => {
        var flag = false
        // 如果不一致，则保留该行
        for (const key in params) {
          if (ele[key] != params[key]) {
            flag = true
            break
          }
        }
        return flag
      })
      // 如果全部删除后没有可以点击的一行了，需要加一行空行
      if (!this.paramsForm.paramsList.length) {
        this.addParamsLine()
      }
    },
    // 选中某一行修改或移除
    selectHeaderItem(row, column, event) {
      this.selectedFundRow = row
      if (event.target.innerText == "删除") {
        this.removeHeaderFundBtn(this.selectedFundRow)
      }
    },
    // 删除指定行
    removeHeaderFundBtn(params) {
      this.headerForm.headerList = this.headerForm.headerList.filter((ele) => {
        var flag = false
        // 如果不一致，则保留该行
        for (const key in params) {
          if (ele[key] != params[key]) {
            flag = true
            break
          }
        }
        return flag
      })
      // 如果全部删除后没有可以点击的一行了，需要加一行空行
      if (!this.headerForm.headerList.length) {
        this.addHeaderLine()
      }
    },
    /** 查询接口信息列表 */
    getList() {
      this.loading = true;
      listInterface(this.queryParams).then(response => {
        this.interfaceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        interfaceName: null,
        interfaceCode: null,
        requestType: null,
        header: null,
        params: null,
        result: null,
        interfacePath: null,
        relationTables: null,
        frontIds: null,
        postIds: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加接口信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInterface(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改接口信息";
      });
    },
    previewInfo(){
      this.openPreView = true;
      let form = {
        'interfaceName':this.form.interfaceName,
        'interfaceCode':this.form.interfaceCode,
        'header':JSON.stringify(this.headerForm.headerList),
        'params':JSON.stringify(this.paramsForm.paramsList),
        'result':JSON.stringify(this.rebackData),
        'requestType':this.form.requestType,
        'interfacePath':this.form.interfacePath,
        'frontIds':JSON.stringify(this.form.frontIds)
      }
      previewInfo(form).then(res=>{
        this.previewForm = res.data
      })
    },
    cancelPre(){
      this.openPreView =false
    },
    /** 提交按钮 */
    submitForm() {
      let form = {
        'interfaceName': this.form.interfaceName,
        'interfaceCode': this.form.interfaceCode,
        'header': JSON.stringify(this.headerForm.headerList),
        'params': JSON.stringify(this.paramsForm.paramsList),
        'result': JSON.stringify(this.rebackData),
        'requestType': this.form.requestType,
        'interfacePath': this.form.interfacePath,
        'frontIds': JSON.stringify(this.form.frontIds)
      }
      addInterface(form).then(res => {
        if (res.code == '0') {
          this.openPreView = false
          this.open = false
          this.getList();
        }
      })


      // this.$refs["form"].validate(valid => {
      //   if (valid) {
      //     if (this.form.id != null) {
      //       updateInterface(this.form).then(response => {
      //         this.$modal.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addInterface(this.form).then(response => {
      //         this.$modal.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除接口信息编号为"' + ids + '"的数据项？').then(function() {
        return delInterface(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/interface/export', {
        ...this.queryParams
      }, `interface_${new Date().getTime()}.xlsx`)
    },

    append(data) {
      const newChild = { id: id++, label: '',isRoot:false,type:'string',children: [] };
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      data.children.push(newChild);
      console.log(this.rebackData)
    },

    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
    },
  }
};
</script>
<style lang="scss" scoped>
.all {
  width: 100%;
}
.flex-c-a {
  display: flex;
  align-items: center;
  justify-content: space-around;
}
.margin-top-10 {
  margin-top: 10px;
}
.base-form.el-form-item__content {
  margin-left: 0;
}
.add-btn {
  color: #4077F4;
}
.delete-btn {
  color: #f56c6c;
}
.small-width-ipt{
  width: 100px !important;
  margin-right: 10px;
}
.el-checkbox{
  margin-left: 10px;
  margin-right: 10px;

}
.small-width-select{
  width: 120px;
  margin-right: 10px;
}
.actions{
  margin-left: 10px;
}
::v-deep .el-tree-node__content{
  height: 45px;
}
</style>
